package swimv2.ejb.control;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

import swimv2.ejb.entity.Capacita;
import swimv2.ejb.entity.Lavoro;
import swimv2.ejb.entity.Utente;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import swimv2.ejb.remote.RicercaAmiciRemote;
import swimv2.ejb.util.GestioneUtenti;


@Stateless(name="RicercaAmici") 
public class RicercaAmici implements RicercaAmiciRemote  {
	@PersistenceContext(unitName="SWIMV2")
	private EntityManager entityManager;
	
	public RicercaAmici()
	{
		
		
	}
	
	@Override
	public List<Utente> cercaUtente(String username,List<Integer> capacita_i)
	{
		Set<Capacita>capacita = new TreeSet<Capacita>();
		for(int id:capacita_i)
		{
			Capacita c = entityManager.find(Capacita.class, id); 
			capacita.add(c);
			
		}
		String ricerca="SELECT DISTINCT u From Utente u WHERE u.username LIKE '%"+username+"%'";
			
		Query query=entityManager.createQuery(ricerca); 
		List <Utente> utentiCandidati=(List<Utente>)query.getResultList(); 
		List<Utente> utenti = new ArrayList<Utente>();
		for(Utente u:utentiCandidati)
		{
			if(u.getCapacita().containsAll(capacita))
				utenti.add(u);
		}
		
		
		return utenti;
		
		
	}
	
	
	
}
